<script setup>
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import UploadFile from '@/components/UploadFile/UploadFile.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import api from '@/api/index.js'
import { getOptions } from '@/utils'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})
// 弹窗标题
const title = computed(() => (props.curRow.id ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  type: '',
  title: '',
  bannerUrl: '',
  sourceUrl: '',
  context: '',
  sort: ''
})
// 是否显示弹窗
const show = ref(false)
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    let resObj = {}
    if (props.curRow.id && show.value) {
      const { resultObject } = await api.getLbtInfo({ id: props.curRow.id })
      resObj = resultObject
      formData.value = { ...formData.value, ...val, ...resObj }
    } else {
      formData.value = {
        type: '',
        title: '',
        bannerUrl: '',
        sourceUrl: '',
        context: '',
        sort: ''
      }
    }
  },
  { deep: true, immediate: true }
)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      type: '',
      title: '',
      bannerUrl: '',
      sourceUrl: '',
      context: '',
      sort: ''
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = { ...formData.value, ...info }
    await api.editLbt(params)
    message.success('编辑成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 新增数据
const addItem = async (info) => {
  try {
    submitLoading.value = true
    let params = { ...formData.value, ...info }
    await api.addLbt(params)
    message.success('新增成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('init')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = falseyyg
    }, 30)
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.id) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  if (formData.value.context === '<p><br></p>') {
    formData.value.context = ''
  }
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}

defineExpose({ open })
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    width="1300px"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item label="类型" name="type" :rules="[{ required: true, message: '请选择' }]">
        <a-select
          v-model:value="formData.type"
          :options="getOptions('banner_type')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item label="主题" name="title" :rules="[{ required: true, message: '请输入' }]">
        <a-input v-model:value="formData.title" allowClear />
      </a-form-item>
      <a-form-item
        label="轮播图片/视频"
        name="bannerUrl"
        :rules="[{ required: true, message: '请上传' }]"
      >
        <a-form-item-rest>
          <UploadFile v-model="formData.bannerUrl" :limit="1" />
          <span style="color: red"
            >提示：为保证展示效果，图片尺寸为375*203，视频格式为MP4，视频大小不可超过200M</span
          >
        </a-form-item-rest>
      </a-form-item>
      <!-- <a-form-item label="资源路径" name="sourceUrl" :rules="[{ required: true, message: '请输入' }]">
        <a-input v-model:value="formData.sourceUrl" allowClear />
      </a-form-item> -->
      <a-form-item label="内容" name="context" :rules="[{ required: true, message: '请输入' }]">
        <a-form-item-rest>
          <!-- <FullEditor v-model="formData.context" /> -->
          <QuillEditor
            toolbar="full"
            contentType="html"
            v-model:content="formData.context"
            theme="snow"
            placeholder="请输入"
          >
          </QuillEditor>
        </a-form-item-rest>
      </a-form-item>
      <a-form-item label="排序" name="sort" :rules="[{ required: true, message: '请输入' }]">
        <a-input-number :min="0" v-model:value="formData.sort" allowClear />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>